package com.metaera.app.data.rx;

import android.util.Log;

import com.metaera.app.controller.core.RequestPresenter;
import com.metaera.app.controller.view.core.IStatusView;
import com.metaera.app.data.model.BasicResponse;

import java.net.ConnectException;

import androidx.core.util.Consumer;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class ResponseObserver<T extends BasicResponse> implements Observer<T> {

    private final IStatusView mView;

    private Consumer<T> mConsumer;

    private RequestPresenter mPresenter;


    public ResponseObserver(RequestPresenter presenter, IStatusView view, Consumer<T> consumer) {
        this.mView = view;
        this.mConsumer = consumer;
        this.mPresenter = presenter;
    }


    @Override
    public void onSubscribe(Disposable d) {
        this.mPresenter.add(d);
    }


    @Override
    public void onNext(T t) {

        if (!t.isSucceed()) { // 失败
            Exception exception;

//            if (t.getCode() == 401) { // 登录过期
//                exception = new UnauthorizedException(t.getMsg());
//
//            } else if (t.getCode() == 1003) { // 1003 注册失败，用户已存在
//                exception = new RegisterException(t.getMsg());
//
//            } else if (t.getCode() == 1002) { // 1002 用户注册未完善用户信息
//
//                UserDetailEntity user = (UserDetailEntity) t.getData();
//                String token = null;
//
//                if (user != null) {
//                    token = user.getToken();
//                }
//
//                exception = new IncompleteInformationException(token);
//
//            } else {
                exception = new Exception(t.getMessage());
//            }

            onError(exception);

        } else if (mConsumer != null) { // 成功

            try {

                mConsumer.accept(t);

                if (mView != null) {
                    mView.complete();
                }

            } catch (Exception e) {
                onError(e);
            }

        }

    }


    @Override
    public void onError(Throwable e) {
        e.printStackTrace();

        if (mView != null) {
            if (e instanceof ConnectException) {
                mView.offline();

            } else {
                mView.failure(e);

            }
        }

    }


    @Override
    public void onComplete() {
        Log.d("ResponseObserver", "onComplete");
//
//        if (mView != null) {
//            //mView.complete();
//        }
    }

}
